package com.xteam.ecsystem.action;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xteam.ecsystem.base.Constant;
import com.xteam.ecsystem.base.EnableState;
import com.xteam.ecsystem.base.UserLoginBean;
import com.xteam.ecsystem.entities.BaseReceiveAddress;
import com.xteam.ecsystem.service.front.FrontCartService;
import com.xteam.ecsystem.service.front.FrontOrderService;
import com.xteam.ecsystem.service.front.FrontUserAddrService;
import com.xteam.ecsystem.system.ConfigManager;
import com.xteam.ecsystem.utils.FrontUtil;
import com.xteam.ecsystem.utils.StringUtil;

/**
 * 商品请求控制层。
 * @author Chrise
 */
@Controller
public class OrderAction {
	
	@Autowired
	private ConfigManager cfgManager;
	
	@Autowired
	private FrontOrderService foService;
	
	@Autowired
	private FrontUserAddrService fuaService;
	
	@Autowired
	private FrontCartService fcsService;
	
	/**
	 * 设置响应类型
	 * @author liuzhi Feb 18, 2013
	 * @param request
	 * @param response
	 */
	public void setToBeJsonType(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
	}
	
	/**
	 * 获取购物车商品列表请求。
	 * @author ls 2013-01-29 14:31:03
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/order/cartorder.xhtml", method = RequestMethod.GET)
	public String cartorder(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			UserLoginBean ulb = FrontUtil.checkUserLogin(request, response);
			model.put(Constant.VAR_MEMBERID.value(), ulb.getUserId());
			model.put(Constant.VAR_PAGEINDEX.value(), FrontUtil.getIntegerParam(request, "index", 1));
			model.put(Constant.VAR_PAGESIZE.value(), this.cfgManager.getSystemConfig().getSscGlpagesize());
			
		}
		
		return template;
	}
	
	@RequestMapping(value = "/order/orderDetail.xhtml", method = RequestMethod.GET)
	public String orderDetail(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			UserLoginBean user = FrontUtil.checkUserLogin(request, response);
			
			//用户ID
			String userId = user.getUserId();
			//登录状态
			boolean flag = user.isLogin();
			
			BaseReceiveAddress bra = new BaseReceiveAddress();
			
			if(flag){
				boolean addr = this.fuaService.hasAddress(userId);
				
				if(addr){
					bra = this.fuaService.getReceiverInfo(userId);
					
					//检查该地区是否支持货到付款
					model.put(Constant.VAR_ISCASHONDELIVERY.value(), foService.isCashOnDelivery(bra.getBraDistrict()));
					request.getSession().setAttribute("receiverInfo", bra);
				}else{
					response.sendRedirect(request.getContextPath()+"/order/fillReceipt.xhtml");
				}
			}else{
				bra = null;
				response.sendRedirect(request.getContextPath()+"/order/loginOrRegister.xhtml");
			}
			
			model.put(Constant.VAR_RECEIVERINFO.value(), bra);
			model.put(Constant.VAR_MEMBERID.value(), userId);
			
		}
		
		return template;
	}
	
	@RequestMapping(value = "/order/orderDetail.xhtml", method = RequestMethod.POST)
	public String orderDetailPost(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			UserLoginBean user = FrontUtil.checkUserLogin(request, response);
			//用户ID
			String userId = user.getUserId();
			//登录状态
			boolean flag = user.isLogin();
			
			//获取收货地址
			String braId = FrontUtil.getStringParam(request, "braId", "");
			BaseReceiveAddress bra = new BaseReceiveAddress();
			
			if(braId != ""){
				//查询获得收货地址
				bra = fuaService.getReceiverInfoById(braId);
			}else{
				//表单获得收货地址
				bra.setBraCountry(FrontUtil.getStringParam(request, "braCountry", ""));
				bra.setBraProvince(FrontUtil.getStringParam(request, "braProvince", ""));
				bra.setBraCity(FrontUtil.getStringParam(request, "braCity", ""));
				bra.setBraDistrict(FrontUtil.getStringParam(request, "braDistrict", ""));
				bra.setBraConsignee(FrontUtil.getStringParam(request, "braConsignee", ""));
				bra.setBraDetail(FrontUtil.getStringParam(request, "braDetail", ""));
				bra.setBraZipcode(FrontUtil.getStringParam(request, "braZipcode", ""));
				bra.setBraPhone(FrontUtil.getStringParam(request, "braPhone", ""));
				bra.setBraMobile(FrontUtil.getStringParam(request, "braMobile", ""));
				bra.setBraTime(FrontUtil.getStringParam(request, "braTime", ""));	
				bra.setBraIsdefault(0);
				bra.setBraMember(userId);
				
				if(flag){
					fuaService.saveOrUpdateObj(bra, bra.getBraId());
				}	
			}
			
			request.getSession().setAttribute("receiverInfo", bra);
			//检查该地区是否支持货到付款
			model.put(Constant.VAR_ISCASHONDELIVERY.value(), foService.isCashOnDelivery(bra.getBraDistrict()));
			model.put(Constant.VAR_RECEIVERINFO.value(), bra);
			model.put(Constant.VAR_MEMBERID.value(), userId);
		}
		
		return template;
	}
	
	@RequestMapping(value = "/loginOrRegister.xhtml", method = RequestMethod.POST)
	public String listPost(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			//设置数据
	
		}
		return template;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/order/submit.xhtml", method = RequestMethod.POST)
	public String submitOrder(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			UserLoginBean ulb = FrontUtil.checkUserLogin(request, response);
			//用户ID
			String userId = ulb.getUserId();
			
			//登录状态
			//boolean flag = ulb.isLogin();
			
			int count = fcsService.countCartGoods(userId);
			if (count > 0){
				//获取设置数据
				List list = foService.getPriceChange(userId);
				if(list != null){
					//显示价格变化列表
					model.put(Constant.VAR_PRICECHANGEINFO.value(), list);
				}else {
					//从session中获取收货人信息
					BaseReceiveAddress bra = (BaseReceiveAddress) request.getSession().getAttribute("receiverInfo");
					
					if(bra == null){
						response.sendRedirect(request.getContextPath() + "/index.xhtml");
						return null;
					}
					
					// 配送费
					double yunfei = Double.parseDouble(FrontUtil.getStringParam(request, "btn_postage", "0"));
					// 购物券抵用金额
					double couponPrice = Double.parseDouble(FrontUtil.getStringParam(request, "btn_coupon", "0"));
					// 购物券ID
					String couponId = FrontUtil.getStringParam(request, "btn_coupon_id", "");
					// 用户备注
					String remark = FrontUtil.getStringParam(request, "remarks", "");
					// 支付方式
					String payMode = FrontUtil.getStringParam(request, "payMode", "");
					// IP地址
					String ip = StringUtil.getIpAddr(request);
					
					// 保存订单信息。为方便事务控制，本段代码全部提到service中去。
					Map<String, Object> map = foService.saveUserOrder(bra, userId, yunfei, couponPrice, couponId, remark, payMode, ip);
				
					if((Boolean)map.get("isSucc")){
						model.put(Constant.VAR_ORDERINFO.value(), map.get("orderInfo"));
					}else{
						response.sendRedirect(request.getContextPath() + "/index.xhtml");
						return null;
					}
				}
			}else {
				model.put(Constant.VAR_CARTGOODSNUM.value(), count);
			}
	
		}
		return template;
	}
	
	@RequestMapping(value = "/order/fillReceipt.xhtml", method = RequestMethod.GET)
	public String receiveInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		//获取模板路径
		String template = FrontUtil.getTemplatePath(request, response, this.cfgManager);
		if (template != null) {
			//设置公共数据
			FrontUtil.setCommons(request, response, model, this.cfgManager.getSystemConfig(), this.cfgManager.getWebConfig());
			
			//设置数据
			UserLoginBean ulb = FrontUtil.checkUserLogin(request, response);
			//用户ID
			String userId = ulb.getUserId();
			//登录状态
			//boolean flag = ulb.isLogin();
			model.put(Constant.VAR_MEMBERID.value(), userId);
		}
		return template;
	}
	
	/**
	 * 查询用户可用的购物券
	 * 
	 * 符合以下条件即可查询相应的购物券：
	 *  1、系统已开启购物券功能
	 * 	2、登录用户
	 * 	3、用户已拥有不同数额的购物券（一张或多张）
	 * 	4、符合购物券使用规则
	 * 
	 * 下单时若使用购物券：
	 * 	1、一次只允许使用一张购物券
	 * 	2、插入购物券使用日志
	 *  3、用户购物券数量执行减少
	 *  4、插入订单与购物券使用记录
	 * 
	 * @author liuzhi 2014-1-3
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/order/getUserCoupons.xhtml", method = RequestMethod.POST)
	public void getUserCoupons(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException, ServletException {
		setToBeJsonType(request, response);
		
		// 如果启用了购物券功能
		if(EnableState.ENABLE.value() == this.cfgManager.getWebConfig().getSwcEbcoupon()){
			String userId = FrontUtil.getStringParam(request, "userId", "");
			String goodsTotal = FrontUtil.getStringParam(request, "goodsTotal", "");
			
			String couponsStr = this.foService.getUserCoupons(userId, goodsTotal);
			response.getWriter().print(couponsStr);
		}
	}

}
